package com.wikilife;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.FrameLayout;

import com.oklib.base.CoreBaseActivity;
import com.wikilife.widget.BottomBar;

import butterknife.BindView;


public class MainActivity extends CoreBaseActivity implements BottomBar.OnItemClickClickListener {


    @BindView(R.id.content_frame)
    FrameLayout contentFrame;
    @BindView(R.id.main_bottom_tablayout)
    BottomBar mBottomBar;
    private String[] mTitles;
    private Fragment mContentCurr;
    private Fragment mContentPrev;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        //7A7E83  FF4683
        mTitles = getResources().getStringArray(R.array.main_bottom_items);
        mBottomBar.addSpaceItem(new SpaceItem(mTitles[0], R.mipmap.tab0_0, R.mipmap.tab0_1));
        mBottomBar.addSpaceItem(new SpaceItem(mTitles[1], R.mipmap.tab1_0, R.mipmap.tab1_1));
        mBottomBar.addSpaceItem(new SpaceItem(mTitles[2], R.mipmap.tab2_0, R.mipmap.tab2_1));
        mBottomBar.addSpaceItem(new SpaceItem(mTitles[3], R.mipmap.tab3_0, R.mipmap.tab3_1));
        mBottomBar.setOnItemClickClickListener(this);

        setDefaultFragment();
    }

    private void setDefaultFragment() {
        mContentCurr = new FragmentIndex();
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.add(R.id.content_frame, mContentCurr, mTitles[0]);
        ft.commitAllowingStateLoss();
    }

    @Override
    public void spaceItemClick(int oldIndex, int newIndex, SpaceItem spaceitem) {
        switchContent(newIndex);
    }

    public void switchContent(int pos) {
        mContentPrev = mContentCurr;
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        mContentCurr = fragmentManager.findFragmentByTag(mTitles[pos]);
        if (mContentCurr == null) {
            switch (pos) {
                case 0:
                    mContentCurr = new FragmentIndex();
                    break;
                case 1:
                    mContentCurr = new FragmentNearBy();
                    break;
                case 2:
                    mContentCurr = new FragmentOrder();
                case 3:
                    mContentCurr = new FragmentMy();
                    break;
            }
        }
        if (!mContentCurr.isAdded()) {
            transaction.hide(mContentPrev).add(R.id.content_frame, mContentCurr, mTitles[pos]).commit();
        } else {
            transaction.hide(mContentPrev).show(mContentCurr).commit();
        }
    }

    @Override
    public void centerButtonClick(View view) {

    }
}
